import React from "react";
import { Link, Routes, Route, Navigate, useNavigate } from "react-router-dom";

const Home = () => {
  return <div>这是home页面</div>;
};

const About = () => {
  return <div>这是about页面</div>;
};

const Login = () => {
  const navigate = useNavigate();
  const fn = () => {
    localStorage.setItem("token", "111");
    navigate("/about");
  };
  return (
    <div>
      这是登录页面 - <button onClick={fn}>btn</button>
    </div>
  );
};

const Auth = (props) => {
  if (localStorage.getItem("token")) {
    return props.children;
  } else {
    return <Navigate to="/login"></Navigate>;
  }
};

const App = () => {
  return (
    <>
      <h2>react-router-v6-路由鉴权</h2>
      <ul>
        <li>
          <Link to="/home">home</Link>
        </li>
        <li>
          <Link to="/about">about</Link>
        </li>
      </ul>

      <hr />

      <Routes>
        {/* 404写法几乎一样，写在最下面 */}
        <Route path="/home" element={<Home />}></Route>
        <Route
          path="/about"
          element={
            // localStorage.getItem("token") ? (
            //   <About />
            // ) : (
            //   <Navigate to="/login"></Navigate>
            // )
            <Auth>
              <About />
            </Auth>
          }
        ></Route>
        <Route path="/login" element={<Login />}></Route>
        <Route path="*" element={<div>404 font found...</div>}></Route>
      </Routes>
    </>
  );
};

export default App;
